#!/usr/bin/env python3
"""
Script: run_clear.py
Function: Delete all nohup.out files in current directory and subdirectories
Author: Converted from bash script
"""

import argparse
import os
import sys
from pathlib import Path


def get_file_size_display(file_path):
    """Convert file size to human readable format"""
    try:
        size = os.path.getsize(file_path)
        if size == 0:
            return "0 bytes"
        elif size < 1024:
            return f"{size} bytes"
        elif size < 1048576:
            return f"{size // 1024} KB"
        else:
            return f"{size // 1048576} MB"
    except OSError:
        return "unknown size"


def main():
    parser = argparse.ArgumentParser(description="Delete all nohup.out files in current directory and subdirectories")
    parser.add_argument('-q', '--quiet', action='store_true',
                       help='Quiet mode, only show summary information')
    args = parser.parse_args()

    # Colors for output (Windows compatible)
    RED = '\033[0;31m'
    GREEN = '\033[0;32m'
    YELLOW = '\033[1;33m'
    BLUE = '\033[0;34m'
    NC = '\033[0m'  # No Color

    found_count = 0
    deleted_count = 0

    if not args.quiet:
        print(f"{BLUE}Starting scan for nohup.out files in current directory and subdirectories...{NC}")
        print()

    # Find all nohup.out files
    nohup_files = []
    for root, dirs, files in os.walk('.'):
        for file in files:
            if file == 'nohup.out':
                nohup_files.append(os.path.join(root, file))

    # Process each file
    for file_path in nohup_files:
        found_count += 1

        if not args.quiet:
            size_display = get_file_size_display(file_path)
            print(f"Found file: {YELLOW}{file_path}{NC} (size: {size_display})")

        # Delete the file
        try:
            os.remove(file_path)
            if not args.quiet:
                print(f"  {GREEN}✓ Deleted{NC}")
            deleted_count += 1
        except OSError as e:
            if not args.quiet:
                print(f"  {RED}✗ Deletion failed (permission issue?): {e}{NC}")

        if not args.quiet:
            print()

    # Output summary
    print("=" * 49)
    print(f"{BLUE}Scan completed!{NC}")
    print(f"Files found: {YELLOW}{found_count}{NC}")
    print(f"Files successfully deleted: {GREEN}{deleted_count}{NC}")

    if found_count == 0:
        print(f"{GREEN}No nohup.out files found in current directory and subdirectories{NC}")
    elif deleted_count == found_count:
        print(f"{GREEN}All nohup.out files successfully deleted!{NC}")
    elif deleted_count > 0:
        failed_count = found_count - deleted_count
        print(f"{YELLOW}{failed_count} files failed to delete, possibly due to permission issues{NC}")
    else:
        print(f"{RED}All deletions failed, please check permissions{NC}")

    print("=" * 49)


if __name__ == "__main__":
    main()
